package org.mark.sell.service.impl;

import org.apache.commons.lang3.ObjectUtils;
import org.mark.common.entity.FreshFood;
import org.mark.common.response.Result;
import org.mark.sell.entity.PromotionInfo;
import org.mark.sell.feign.StorageFreshFoodFeignClient;
import org.mark.sell.mapper.PromotionInfoMapper;
import org.mark.sell.service.PromotionInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class PromotionInfoServiceImpl implements PromotionInfoService {

    @Resource
    private PromotionInfoMapper promotionInfoMapper;

    @Autowired
    private StorageFreshFoodFeignClient storageFreshFoodFeignClient;

    @Override
    public Result page(Integer pageNum, Integer pageSize, String name) {
        LambdaQueryWrapper<PromotionInfo> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(name)) {
            wrapper.like(PromotionInfo::getFreshFoodName, name);
        }
        wrapper.orderByDesc(PromotionInfo::getCreateTime);

        Page<PromotionInfo> page = promotionInfoMapper.selectPage(
                new Page<>(pageNum, pageSize),
                wrapper
        );

        // 获取所有促销商品对应的生鲜信息
        List<PromotionInfo> records = page.getRecords();
        if (!records.isEmpty()) {
            for (PromotionInfo promotion : records) {
                // 查询对应的生鲜信息获取原价
                FreshFood freshFood = storageFreshFoodFeignClient.getById(promotion.getFreshFoodId());
                if (ObjectUtils.isNotEmpty(freshFood)) {
                    promotion.setOriginalPrice(freshFood.getPrice());
                }
            }
        }

        return Result.success(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result save(PromotionInfo promotionInfo) {
        // 检查生鲜是否存在促销信息（不论状态）
        LambdaQueryWrapper<PromotionInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PromotionInfo::getFreshFoodId, promotionInfo.getFreshFoodId());

        PromotionInfo existPromotion = promotionInfoMapper.selectOne(wrapper);
        if (existPromotion != null) {
            return Result.fail("该生鲜已存在促销信息，请通过编辑功能修改");
        }

        // 检查生鲜是否存在
        FreshFood freshFood = storageFreshFoodFeignClient.getById(promotionInfo.getFreshFoodId());
        if (ObjectUtils.isEmpty(freshFood)) {
            return Result.fail("所选生鲜不存在");
        }

        promotionInfo.setFreshFoodName(freshFood.getName());  // 设置生鲜名称
        promotionInfo.setCreateTime(new Date());
        promotionInfo.setCreateBy("admin");
        
        int rows = promotionInfoMapper.insert(promotionInfo);
        return rows > 0 ? Result.success("") : Result.fail("保存失败");
    }

    @Override
    public Result update(PromotionInfo promotionInfo) {
        // 检查是否存在
        PromotionInfo exist = promotionInfoMapper.selectById(promotionInfo.getId());
        if (exist == null) {
            return Result.fail("促销信息不存在");
        }

        // 如果修改了生鲜，检查新的生鲜是否已有其他促销
        if (!exist.getFreshFoodId().equals(promotionInfo.getFreshFoodId())) {
            LambdaQueryWrapper<PromotionInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PromotionInfo::getFreshFoodId, promotionInfo.getFreshFoodId())
                    .ne(PromotionInfo::getId, promotionInfo.getId());

            PromotionInfo otherPromotion = promotionInfoMapper.selectOne(wrapper);
            if (otherPromotion != null) {
                return Result.fail("所选生鲜已存在促销信息");
            }
        }

        promotionInfo.setUpdateTime(new Date());
        promotionInfo.setUpdateBy("admin");
        
        int rows = promotionInfoMapper.updateById(promotionInfo);
        return rows > 0 ? Result.success("") : Result.fail("更新失败");
    }

    @Override
    public Result remove(Integer id) {
        int rows = promotionInfoMapper.deleteById(id);
        return rows > 0 ? Result.success("") : Result.fail("删除失败");
    }
}